package com.sample.springbatch.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.configuration.ListableJobLocator;
import org.springframework.batch.core.converter.DefaultJobParametersConverter;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.support.PropertiesConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 批量任务管理类
 * Created by zwg on 2017/7/25.
 */
@Service
public class BatchJobMgrService {

    Logger logger = LoggerFactory.getLogger(BatchJobMgrService.class);

    @Autowired
    private ListableJobLocator jobLocator;
    @Autowired
    JobLauncher jobLauncher;


    public List<Job> getJobs(){
        Collection<String> jobNames = jobLocator.getJobNames();
        List<Job> jobList = new ArrayList<>();
        if(jobNames!=null && !jobNames.isEmpty()){
            for (String jobName: jobNames) {
                try{
                    jobList.add(jobLocator.getJob(jobName));
                }catch (Exception e){
                    logger.error("not find job {}",jobName);
                }
            }
        }

        return jobList;
    }


    public void runJob(String jobName, String jobParamStr){
        Job job = null;
        try{
            job = jobLocator.getJob(jobName);
        }catch (Exception e){
            logger.error("not find job {}",jobName);
        }
        if(job==null){
            logger.error("not find job {}",jobName);
        }

        JobParameters jobParams = new DefaultJobParametersConverter().getJobParameters(PropertiesConverter.stringToProperties(jobParamStr));
        try{
            jobLauncher.run(job,jobParams);
        }catch (Exception e){

        }

    }
}
